﻿using System.Collections.Generic;
using System.Linq;

namespace CRMS.Models
{
    public class BuildingRep
    {
        private StoreDBDataContext storeDB = new StoreDBDataContext();

        //
        //Query Methods
        /// <summary>
        /// 获取所有的教学楼
        /// </summary>
        /// <returns>返回教学楼集合</returns>
        public IQueryable<TeachingBuilding> GetBuildings()
        {
            return storeDB.TeachingBuildings;
        }
        /// <summary>
        /// 通过ID获取特定教学楼
        /// </summary>
        /// <param name="id">教学楼id</param>
        /// <returns>返回给定ID的教学楼</returns>
        public TeachingBuilding GetBuidingByID(string id)
        {
            return storeDB.TeachingBuildings.SingleOrDefault(b => b.TeachingBuildingId == id.Trim());
        }
        /// <summary>
        /// 通过Name获取特定的教学楼
        /// </summary>
        /// <param name="name">教学楼Name</param>
        /// <returns>返回给定Name的教学楼</returns>
        public TeachingBuilding GetBuildingByName(string name)
        {
            return storeDB.TeachingBuildings.SingleOrDefault(b => b.TeachingBuildingName == name.Trim());
        }
        //
        //Insert/Delete
        /// <summary>
        /// 向数据库中插入一条教学楼记录
        /// </summary>
        /// <param name="building">传给方法一个教学楼对象</param>
        public void Add(TeachingBuilding building)
        {
            storeDB.TeachingBuildings.InsertOnSubmit(building);
        }
        /// <summary>
        /// 从数据库中删除一条教学楼记录
        /// </summary>
        /// <param name="building">传入方法一个教学楼对象</param>
        public void Delete(TeachingBuilding building)
        {
            //先删除关联的所有教室<先删除外键>
            storeDB.Classrooms.DeleteAllOnSubmit(building.Classrooms);
            //再删除教学楼<再删除主键>
            storeDB.TeachingBuildings.DeleteOnSubmit(building);
        }

        //
        //Persistence
        /// <summary>
        /// 向数据库提交更改
        /// </summary>
        public void Save()
        {
            storeDB.SubmitChanges();
        }
    }
}
